package com.meilian.tbcrm.java.tmc.message;

import com.meilian.tbcrm.java.tmc.util.Config;
import com.taobao.api.internal.tmc.TmcClient;
import com.taobao.api.internal.toplink.LinkException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

/**
 * tmc客户端连接管理器
 */
public class TmcClientManager extends Thread {

    private Logger logger = LoggerFactory.getLogger(TmcClientManager.class);

    //运行表示
    public boolean runMark = false;

    //重连测试
    public int connnTime = 3;

    //连接客户端
    private TmcClient client;

    //配置信息
    private Config config ;

    public void initAndStartClient() throws LinkException {
        this.config = new Config("tmcClient.properties");
        this.client = new TmcClient(config.getString("username"), config.getString("password"), config.getString("group.name"));
        this.client.setMessageHandler(new TmcClientMessageHanlder());
        this.startClient();

    }

    public void startClient() throws LinkException {
        this.client.connect(config.getString("connection.url"));
    }


    public void run(){
        while(runMark){
            try {
                if (!this.client.isOnline()) {
                    if (connnTime-- > 0) {
                        this.startClient();
                    }
                    else
                        this.client.close();
                }
                Thread.sleep(1000 * 60 * 20);
            }catch (Exception ex){
                logger.info("连接出现异常,异常信息:{}",ex.getMessage(),ex);
            }

        }
    }

    public void startThread() throws LinkException {
        this.initAndStartClient();
        this.runMark = true;
        this.start();
    }


}
